﻿using Wabo.Dal;
using System;
namespace Wabo.Web.Areas.Manager.Core
{
    public class SessionManager
    {
        public static string AuthorizationKey = "USER_AUTHORIZATION_VALUE";
        public static string AuthorizedUserKey = "USER_AUTHORIZATION_OBJECT";

        public static User AuthorizedUser()
        {
            return (User)ReturnSessionObject(AuthorizedUserKey);
        }

        public static void Authorize(User usr)
        {
            RegisterSessionObject(AuthorizationKey, usr.id);
            RegisterSessionObject(AuthorizedUserKey, usr);
        }
        
        public static void Logout()
        {
            FreeSessionObject(AuthorizationKey);
            FreeSessionObject(AuthorizedUserKey);
        }

        public static bool IsAuthorized()
        {
            try
            {
                var userId = (long)ReturnSessionObject(AuthorizationKey);
                var usr = (User)ReturnSessionObject(AuthorizedUserKey);
                return usr.id == userId;
            }
            catch (Exception)
            {
                return false;
            }
        }
        public static void RegisterSessionObject(string key, object obj)
        {
            System.Web.HttpContext.Current.Session[key] = obj;
        }

        public static void FreeSessionObject(string key)
        {
            System.Web.HttpContext.Current.Session[key] = null;
        }

        public static bool CheckSessionObject(string key)
        {
            return (System.Web.HttpContext.Current.Session[key] != null);
        }

        public static object ReturnSessionObject(string key)
        {
            if (CheckSessionObject(key))
                return System.Web.HttpContext.Current.Session[key];
            return null;
        }
    }
}